package com.zy.list.list

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.zy.list.ListConstant.ARG_FILE_ID
import com.zy.list.R
import com.zy.list.create.CreateOrModifyTitleFragment
import com.zy.storage.DataBaseUtils
import com.zy.storage.doc.DocInfo

//文件操作
class FileOpFragment : BottomSheetDialogFragment() {

    private var fileId = 0L
    private var docInfo: DocInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            fileId = it.getLong(ARG_FILE_ID)
        }

        if (fileId != 0L) {
            //从数据库中取出数据展示
            DataBaseUtils.getDocInfoDao().getDocInfo(fileId).observe(this) {
                //获取文件
                this.docInfo = it
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.dialog_fragment_file_op_layout, container, false)
        view.findViewById<View>(R.id.file_copy).setOnClickListener {
            //复制文件
            dismissAllowingStateLoss()
            docInfo?.let {
                DataBaseUtils.copy(it)
            }
        }

        view.findViewById<View>(R.id.file_delete).setOnClickListener {
            //删除文件
            dismissAllowingStateLoss()
            docInfo?.let {
                DataBaseUtils.delete(it)
            }
        }


        view.findViewById<View>(R.id.file_rename).setOnClickListener {
            //重命名
            dismissAllowingStateLoss()
            docInfo?.let {
                CreateOrModifyTitleFragment.show(
                    parentFragmentManager,
                    it.fileType,
                    it.parentId,
                    it.fileId
                )
            }

        }
        return view
    }

    companion object {

        fun show(parentFragmentManager: FragmentManager, fileId: Long = 0) {
            val ft: FragmentTransaction = parentFragmentManager.beginTransaction()
            val prev: Fragment? = parentFragmentManager.findFragmentByTag("file_op")
            if (prev != null) {
                ft.remove(prev)
            }
            ft.addToBackStack(null)
            val newFragment: DialogFragment = FileOpFragment().apply {
                arguments = Bundle().apply {
                    putLong(ARG_FILE_ID, fileId)
                }
            }
            newFragment.show(ft, "file_op")
        }
    }
}